<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/22
 * Time: 10:10
 */

namespace app\qgroup\controller;


use app\common\Enum\CommonEnum;
use app\common\service\SysConfigService;
use app\common\util\ReturnMsgUtil;
use app\qgroup\model\GroupList;
use app\qgroup\model\QqCodeMapping;
use app\qgroup\service\CodeFactory;
use think\Controller;
use think\Exception;


class Register extends Controller
{
    use ReturnMsgUtil;

    public function index()
    {
        @header("http/1.1 404 not found");
        @header("status: 404 not found");
        echo '404 not found';//直接输出页面错误信息
        exit();
    }

    /**
     * 用户获取注册码
     * @return mixed
     * @throws Exception
     * @throws \think\exception\DbException
     */
    public function getCode()
    {
        $qq = input('qq');
        $qcm = QqCodeMapping::get(['qq'=>$qq]);
        if (!$qcm){
            $cf = CodeFactory::getInstance();
            $code = $cf->getNewCode($qq);
            $qcm = QqCodeMapping::create([
                'qq'=>$qq
                ,'code'=>$code
                ,'status'=>CommonEnum::COMMON_VALID
            ]);
        }
        $qcms = new QqCodeMapping();
        $num = $qcms->count();
        if ($num > SysConfigService::getSysConfig('app.first.count.user')  && !$qcm->status){
            $this->assign('code','已停止免费发放注册码');
            $this->assign('style_display','block');
        }else {
            $r = $qcm->save(['pay_status'=>CommonEnum::COMMON_VALID]);
            if ($r === false && $qcm->pay_status == CommonEnum::COMMON_INVALID){
                throw new Exception('邀请码生成中，请刷新页面试试');
            }
            $this->assign('code', $qcm->code);
            $this->assign('style_display','none');
        }
        return $this->fetch();
    }

    /**
     * 填写注册码
     * @return string
     * @throws \think\exception\DbException
     */
    public function putCode()
    {
        $qq = input('qq');
        $code = input('code');
        $qcm = QqCodeMapping::get(['qq'=>$qq]);
        if ($qcm->code == $code){
            $r = $qcm->save(['status'=>CommonEnum::COMMON_VALID,'activation_state'=>CommonEnum::COMMON_VALID]);
            if ($r === false){
                return $this->errorInfo('数据保存异常');
            }
            return $this->successInfo('注册成功');
        }
    }
}